package com.sky.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String password = DigestUtils.md5DigestAsHex(employeeLoginDTO.getPassword().getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 改密码
     *
     * @param passwordEditDTO
     */
    @Transactional
    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        //数据校验非空判断提升代码健壮性
        if (passwordEditDTO.getOldPassword() == null || passwordEditDTO.getNewPassword().length() == 0) {
            //密码修改失败
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        passwordEditDTO.setEmpId(BaseContext.getCurrentId());
        passwordEditDTO.setOldPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes()));
        passwordEditDTO.setNewPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        /*根据就密码和id查找员工*/
        log.info("id是" + BaseContext.getCurrentId());
        /*对原密码进行校验*/
        Employee employee2 = new Employee();
        employee2.setId(BaseContext.getCurrentId());
        employee2.setPassword(passwordEditDTO.getOldPassword());
        Employee employee = employeeMapper.getByIdAndPassword(employee2);

        if (employee == null) {
            //密码修改失败
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        Employee employee1 = new Employee();
        employee1.setId(passwordEditDTO.getEmpId());
        employee1.setPassword(passwordEditDTO.getNewPassword());
//        employee1.setUpdateTime(LocalDateTime.now());
//        employee1.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.editEmp(employee1);

    }

    /**
     * 禁用启用
     *
     * @param status
     * @param id
     */
    @Transactional
    @Override
    public void editStatus(Integer status, Long id) {
        //非空判断
        if (status == null || id == null) {
            throw new BaseException(MessageConstant.UNKNOWN_ERROR);
        }
        Employee employee = Employee
                .builder()
                .status(status)
                .id(id)
                .build();
//                .updateTime(LocalDateTime.now())
//                .updateUser(BaseContext.getCurrentId())

        employeeMapper.editEmp(employee);
    }

    /**
     * 分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        //非空判断
        if (employeePageQueryDTO.getPage() == 0) {
            employeePageQueryDTO.setPage(1);
        }
        if (employeePageQueryDTO.getPageSize() == 0) {

            employeePageQueryDTO.setPageSize(5);
        }
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> employeePage = employeeMapper.query(employeePageQueryDTO.getName());
        return new PageResult(employeePage.getTotal(), employeePage.getResult());
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Result getById(Long id) {
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        Employee employee = new Employee();
        employee.setId(id);

        EmployeeDTO employeeDTO = new EmployeeDTO();

        Employee byEmp = employeeMapper.getById(employee);
        BeanUtils.copyProperties(byEmp, employeeDTO);
        return Result.success(employeeDTO);
    }

    /**
     * 修改员工信息
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Result updateEmp(EmployeeDTO dto) {
        if (dto == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        Employee employee = new Employee();
        BeanUtils.copyProperties(dto, employee);
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.editEmp(employee);
        return Result.success();
    }

    /**
     * 添加员工
     *
     * @param employeeDTO
     * @return
     */
    @Transactional
    @Override
    public Result addEmp(EmployeeDTO employeeDTO) {
        //非空判断
        if (employeeDTO.getUsername() == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //判断用户名是否已经存在
        Employee byUsername = employeeMapper.getByUsername(employeeDTO.getUsername());
        if (byUsername != null) {
            return Result.error(MessageConstant.ACCOUNT_EXIT_FOUND);
        }
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        //账号状态
        employee.setStatus(StatusConstant.ENABLE);
        //账号密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes(StandardCharsets.UTF_8)));
        //更新创建时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        //更新修改用户
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        //调用dao层
        employeeMapper.addEmp(employee);
        return Result.success();
    }

}
